//
//  ChongzhiVC.m
//  SSC
//
//  Created by 红沙尘 on 17/6/11.
//  Copyright © 2017年 红沙尘. All rights reserved.
//

#import "ChongzhiVC.h"
#import "WebController.h"
#import "SecurityUtil.h"

#import <CommonCrypto/CommonDigest.h>
#import <JHFSDK/JHFSDK.h>
#import <JHFSDK/JHFOrder.h>
#define kScreenWidth [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height

typedef NS_ENUM(NSInteger, PayType) {
    PayTypeWXPay = 100,//微信支付
    PayTypeAlipay = 101,//支付宝支付
    PayTypeBankcard = 102,//储蓄卡支付
};


@interface ChongzhiVC ()
{
    __weak IBOutlet NSLayoutConstraint *lineA;
    __weak IBOutlet NSLayoutConstraint *lineB;
    __weak IBOutlet UIButton *sureBtn;
    __weak IBOutlet UILabel *typeLabel;
    
    __weak IBOutlet UITextField *moneyField;
}

@end

@implementation ChongzhiVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setTitle:@"用户充值"];
    typeLabel.text = @"微信支付";
}

- (void)setupUI {
    lineA.constant = LineHeight;
    lineB.constant = LineHeight;
    
    sureBtn.layer.cornerRadius  = 2;
    sureBtn.layer.masksToBounds = YES;
    
    [moneyField becomeFirstResponder];
}

- (IBAction)pay {
    
    if ([moneyField.text floatValue] == 0) {
        [MTool showMessage:@"请输入充值金额" inView:self.view];
        return;
    }

    NSString *payType = @"";
    
    if ([typeLabel.text isEqualToString:@"微信支付"]) {
        payType = @"0";
    } else if ([typeLabel.text isEqualToString:@"支付宝支付"]) {
        payType = @"1";
    }
    
    [LoadingView show];
    
    WeakSelf
    
    [SSCRequest rechargeAmount:moneyField.text
                          type:payType
                       success:^(NSDictionary *responseObject)
    {
        [LoadingView diss];
        
        NSDictionary *data = responseObject[@"data"];
        NSLog(@"data = %@",data);
        [weakSelf payWithMerorderid:[NSString safeString:data[@"ordernumber"]]
                           paymoney:[NSString safeString:data[@"paymoney"]]
                             userid:[NSString safeString:data[@"uid"]]];
        
   } fail:^(NSError *error) {
       [LoadingView diss];
   }];
}

- (IBAction)selectType {

    WeakSelf
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"支付方式"
                                                                   message:nil
                                                            preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"微信支付"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action)
                      {
                          typeLabel.text = @"微信支付";
                          [weakSelf payWithType:PayTypeWXPay];
                      }]];
    
    [alert addAction:[UIAlertAction actionWithTitle:@"支付宝支付"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action)
                      {
                          typeLabel.text = @"支付宝支付";
                          [weakSelf payWithType:PayTypeAlipay];
                      }]];

    [alert addAction:[UIAlertAction actionWithTitle:@"储蓄卡快捷支付"
                                              style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * _Nonnull action)
                      {
                          typeLabel.text = @"储蓄卡快捷支付";
                          [weakSelf payWithType:PayTypeBankcard];
                      }]];
    
    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];

    [self presentViewController:alert animated:YES completion:nil];
}

- (void)payWithMerorderid:(NSString *)merorderid paymoney:(NSString *)paymoney userid:(NSString *)userid{

    NSString *host = @"http://www.jhpay.com/mobile/payment.jsp";
    
    NSString *args = [NSString stringWithFormat:@"version=1.0&merid=26100549&mername=北京满经海建科技有限公司&policyid=000001&merorderid=%@&paymoney=%@&productname=商品&productdesc=商品支付&userid=%@&username=&email=&phone=&extra=&custom=&redirect=1&redirecturl=",merorderid,paymoney,userid];
    
    NSString *md5 = [NSString stringWithFormat:@"%@v8mqyn01zmfta2597mmpqfj0j1fkz9vc",args];
    
    NSString *url = [NSString stringWithFormat:@"%@?%@&md5=%@",host,args,[MTool MD5:md5]];
    
    WebController *web = [[WebController alloc] init];
    web.html_url = url;
    [self.navigationController pushViewController:web animated:YES];
}

//直接选择支付方式，不再进入支付列表
- (void)payWithType:(PayType)payType {
    
    //商户订单
    JHFOrder *order = [[JHFOrder alloc] init];
    order.version = @"1.0";
    order.merid = @"10000198";
    order.mername = @"北京顺信益信息技术有限公司";
    order.policyid = @"000001";
    order.merorderid = @"170216103434917744";
    order.paymoney = @"1";
    order.productname = @"冠石钱包快捷充值";
    order.productdesc = @"冠石钱包快捷充值";
    order.userid = @"97608";
    order.username = @"刘雄刚";
    order.email = @"GuanshiQB@google.com";
    order.phone = @"18353367661";
    order.extra = @"extra";
    order.custom = @"custom";
    //order.ostype = @"ios";
    order.md5 = [self MD5:order];
    //order.cardtype = @""; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
    
    if (payType == PayTypeWXPay) {
        order.cardtype = @"5"; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
        //聚合富支付
        UINavigationController *navigationController = [[JHFSDK sharedInstance] payOrder:order
                                                                              fromScheme:@"juhefu"
                                                                          viewController:self
                                                                                callback:^(NSDictionary *resultDict) {
            NSLog(@"weixinweixinweixinweixin = %@", resultDict);
            
            //        [self dismissViewControllerAnimated:YES completion:nil];
        }];
        
        if(navigationController!=nil) {
            [self presentViewController:navigationController animated:YES completion:nil];
        }
    } else if (payType == PayTypeAlipay) {
        order.cardtype = @"6"; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
        //聚合富支付
        UINavigationController *navigationController = [[JHFSDK sharedInstance] payOrder:order
                                                                              fromScheme:@"juhefu"
                                                                          viewController:self
                                                                                callback:^(NSDictionary *resultDict)
        {
            NSLog(@"ccccccccccccccccc = %@", resultDict);
            if ([resultDict[@"resultStatus"] intValue] == 9000) {
                [MTool showAlertController:self message:@"支付成功"];
            } else {
                [MTool showAlertController:self message:resultDict[@"memo"]];
            }
            
            //        [self dismissViewControllerAnimated:YES completion:nil];
        }];
        
        if(navigationController!=nil) {
            [self presentViewController:navigationController animated:YES completion:nil];
        }
    } else if (payType == PayTypeBankcard) {
        order.cardtype = @"2"; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
        //聚合富支付
        UINavigationController *navigationController = [[JHFSDK sharedInstance] showControllerWithPayOrder:order
                                                                                                fromScheme:@"juhefu"
                                                                                            viewController:self
                                                                                                  callback:^(NSDictionary *resultDict)
        {
            NSLog(@"ccccccccccccccccc = %@", resultDict);
            if ([resultDict[@"resultStatus"] intValue] == 9000) {
                [MTool showAlertController:self message:@"支付成功"];
            } else {
                [MTool showAlertController:self message:resultDict[@"memo"]];
            }
        }];
        
        if(navigationController!=nil) {
            [self presentViewController:navigationController animated:YES completion:nil];
        }
    }
//    else if (sender.tag == 103) {
//        order.cardtype = @"1"; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
//        //聚合富支付
//        UINavigationController *navigationController = [[JHFSDK sharedInstance] showControllerWithPayOrder:order fromScheme:@"juhefu" viewController:self callback:^(NSDictionary *resultDict) {
//            
//        }];
//        
//        if(navigationController!=nil) {
//            [self presentViewController:navigationController animated:YES completion:nil];
//        }
//    } else {
//        order.cardtype = @"0"; //5: 微信支付；6: 支付宝；2:储蓄卡快捷; 1:信用卡快捷;
//        //聚合富支付
//        UINavigationController *navigationController = [[JHFSDK sharedInstance] showControllerWithPayOrder:order fromScheme:@"juhefu" viewController:self callback:^(NSDictionary *resultDict) {
//            
//        }];
//        
//        if(navigationController!=nil) {
//            [self presentViewController:navigationController animated:YES completion:nil];
//        }
//    }
    
    
    
    
}

// MD5, 因为涉及到商户私钥，建议放在商户服务端进行
- (NSString*)MD5:(JHFOrder *)order {
    
    NSArray *array = @[[NSString stringWithFormat:@"version=%@", order.version?:@""],
                       [NSString stringWithFormat:@"merid=%@", order.merid?:@""],
                       [NSString stringWithFormat:@"mername=%@", order.mername?:@""],
                       [NSString stringWithFormat:@"policyid=%@", order.policyid?:@""],
                       [NSString stringWithFormat:@"merorderid=%@", order.merorderid?:@""],
                       [NSString stringWithFormat:@"paymoney=%@", order.paymoney?:@""],
                       [NSString stringWithFormat:@"productname=%@", order.productname?:@""],
                       [NSString stringWithFormat:@"productdesc=%@", order.productdesc?:@""],
                       [NSString stringWithFormat:@"userid=%@", order.userid?:@""],
                       [NSString stringWithFormat:@"username=%@", order.username?:@""],
                       [NSString stringWithFormat:@"email=%@", order.email?:@""],
                       [NSString stringWithFormat:@"phone=%@", order.phone?:@""],
                       [NSString stringWithFormat:@"extra=%@", order.extra?:@""],
                       [NSString stringWithFormat:@"custom=%@", order.custom?:@""]];
    
    NSString *md5Key = @"yyaeuz9ayypraeuz9ayypraeuz9ayypr";
    
    NSString *string =  [array componentsJoinedByString:@"&"];
    string = [NSString stringWithFormat:@"%@%@", string, md5Key];
    
    const char *pointer = [string UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(pointer, (CC_LONG)strlen(pointer), md5Buffer);
    
    NSMutableString *md5String = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [md5String appendFormat:@"%02x",md5Buffer[i]];
    
    return md5String;
    
}



@end
